import { REMOVE_TODO, SET_DOING, SET_STATUS, SET_TODO, SET_TODO_LIST } from "@/store/actionType"
import { ITodo, TODO_STATUS } from "@/typing"
import { Store, useStore } from "vuex"
import {watch} from 'vue'

interface IUseTodo {
    setTodo: (value: string) => void
    setTodoList: () => void,
    removeTodo: (id: number) => void,
    setStatus: (id: number) => void,
    setDoing: (id: number) => void,
}

interface IUseLocalStorage {
    getLocalStorage: () => ITodo[],
    setLocalStorage: (todoList: ITodo[]) => void
}

function useTodo(): IUseTodo {

    const store: Store<any> = useStore()
    const { getLocalStorage, setLocalStorage }: IUseLocalStorage = useLocalStorage()

    watch(() =>{
        return store.state.list
    },(todoList) =>{
        setLocalStorage(todoList)
    })

    function setTodo(value: string): void {
        const todo: ITodo = {
            id: Math.random(),
            content: value,
            status: TODO_STATUS.WILLDO
        }

        store.dispatch(SET_TODO, todo)
        // setLocalStorage(store.state.list)
    }

    function setTodoList() {
        store.dispatch(SET_TODO_LIST, getLocalStorage())
    }

    function setStatus(id: number): void {
        store.dispatch(SET_STATUS, id)
        // setLocalStorage(store.state.list)
    }

    function removeTodo(id: number): void {
        store.dispatch(REMOVE_TODO, id)
        // setLocalStorage(store.state.list)
    }

    function setDoing(id: number): void {
        store.dispatch(SET_DOING, id)
        // setLocalStorage(store.state.list)
    }

    return {
        setTodo,
        setTodoList,
        removeTodo,
        setStatus,
        setDoing
    }
}


function useLocalStorage(): IUseLocalStorage {
    function getLocalStorage(): ITodo[] {
        return JSON.parse(localStorage.getItem('todoList') || '[]')
    }
    function setLocalStorage(todoList: ITodo[]): void {
        console.log(todoList);
        localStorage.setItem('todoList', JSON.stringify(todoList))
    }
    return {
        getLocalStorage,
        setLocalStorage
    }
}
export {
    useTodo,
    IUseTodo
}